package com.ogawa.base.base

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.ogawa.base.bean.LoadState

abstract class BaseVMActivity <VM : BaseViewModel>: BaseActivity() {
    lateinit var mViewModel: VM
    protected abstract fun providerVMClass(): Class<VM>?
    protected abstract fun observeVM()

    private fun initVM() {
        providerVMClass()?.let { viewModel ->
            mViewModel =ViewModelProvider(this).get(viewModel)
            mViewModel.let(lifecycle::addObserver)
            mViewModel.loadState.observe(this, Observer {
                when (it) {
                    is LoadState.Loading -> {
                        showLoadingDialog(canceledOnTouchOutside = false)
                    }
                    is LoadState.Fail -> {
                        dismissLoadingDialog()
                        ToastUtils.showShort(it.msg)
                        LogUtils.e(it.msg)
                    }
                    is LoadState.Success -> {
                        dismissLoadingDialog()
                    }
                }
            })
        }
    }
    override fun initView() {
        super.initView()
        initVM()
        observeVM()

    }
}